package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadApiService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.MinioException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

@Service
public class FileUploadApiServiceImpl implements FileUploadApiService {
    @Autowired
    private MinioConstantProperties  minioConstantProperties;
    @Autowired
    private MinioClient minioClient;
    @Override
    @SneakyThrows
    public String FileUploadApiController(MultipartFile file) {
        if (ImageIO.read(file.getInputStream())==null){
            throw new GuiguException(500,"没有上传文件");
        }

        // 创建桶
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
        }
        String bucketName = minioConstantProperties.getBucketName();
        String datalogName="/"+ DateUtil.today()+"/";
        String fileName = IdUtil.randomUUID().replace("-","");
        String extName = FileUtil.extName(file.getOriginalFilename());
        String objectName=datalogName+fileName+"."+extName;


        // Upload known sized input stream.
        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                                file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        System.out.println(minioConstantProperties.getEndpointUrl() +"/"+ minioConstantProperties.getBucketName() + objectName);
        return minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+objectName;
    }


}
